<template>
  <div class="pages deliveryOrderAdd">
    <div class="tableSearch">
      <el-button type="primary" @click="goBack()" size="mini">返回</el-button>
      <el-button type="primary" @click="submitForm('formdata')" size="mini">保存</el-button>
      <el-button type="primary" @click="healthOrder()" size="mini">取来源单</el-button>
    </div>

    <el-form :model="formdata" :rules="rules" ref="formdata" label-width="120px" size="mini">
      <el-row>
        <el-col :span="8">
          <el-form-item label="企业客户：">
            <el-input v-model="formdata.shopName" placeholder="请取来源单获取企业客户" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="入库仓库：" prop="warehouseId">
            <el-select v-model="formdata.warehouseId" @change="getwarehouseName">
              <el-option
                v-for="item in cangArray"
                :key="item.index"
                :label="item.repositoryName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="退货日期：" prop="returnDate">
            <el-date-picker
              v-model="formdata.returnDate"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择退货日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据日期：" prop="orderDate">
            <el-date-picker
              v-model="formdata.orderDate"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              type="date"
              disabled
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据号：">
            <el-input v-model="formdata.purchaseinCode" placeholder="单据号自动生成" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 物料表格 -->
    <div class="tableMain">
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column type="index" label="#" width="25"></el-table-column>
        <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
        <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
        <el-table-column prop="goodsName" label="商品" align="center"></el-table-column>
        <el-table-column prop="goodsBatchNumber" label="商品批号" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.isBatch === '1'">{{scope.row.goodsBatchNumber}}</span>
            <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
          </template>
        </el-table-column>
        <!-- 集团订单新加功能5/31 -->
        <el-table-column prop="dateInProduced" label="生产日期" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.isBatch === '1'">{{scope.row.dateInProduced}}</span>
            <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goodsSpec" label="商品规格" align="center">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.goodsSpec" :key="index">
              <span>{{item.paramName}} :</span>
              <span>{{item.paramValue}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
        <el-table-column prop="returnNum" label="数量" align="center" width="150">
          <template slot-scope="scope">
            <input
              class="commonInput"
              v-model="scope.row.returnNum"
              size="mini"
              type="text"
              style="width:100px"
              value="1"
              min="0"
              oninput="if(value.length>8)value=value.slice(0,8)"
              onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
              onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}"
            />
          </template>
        </el-table-column>
        <el-table-column prop="goodsPrice" label="销售价" align="center"></el-table-column>
        <el-table-column prop="goodsAmount" label="总价" align="center">
          <template slot-scope="scope">
            <span>{{(Number(scope.row.goodsPrice)*Number(scope.row.returnNum)).toFixed(2)}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" @click="handleCancel(scope.$index)" size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 价钱计算 -->
    <div class="th-right">
      <el-form :model="formdata" :rules="rules" label-width="120px" size="mini">
        <el-row>
          <el-col :span="10">&nbsp;</el-col>
          <el-col :span="6">
            <el-form-item label="操作员：">
              <el-input v-model="formdata.creator" disabled></el-input>
            </el-form-item>
            <el-form-item label="备注：">
              <el-input v-model="formdata.remark" type="textarea" maxlength="50"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退货金额:" prop="priceTotal">
              <el-input label-text-align="right" v-model="returnAmount" disabled></el-input>
            </el-form-item>
            <el-form-item label="运费：" prop="freight">
              <el-input v-model="formdata.freight" type="text" min="0"></el-input>
            </el-form-item>
            <el-form-item label="退货总金额：">
              <el-input v-model="formdataAllTotal" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 取来源单选择弹出框 -->
    <el-dialog
      title="销售出库单"
      class="addshopname"
      :visible.sync="dialogGet"
      :closeOnClickModal="false"
      :closeOnPressEscape="false"
      width="60%"
    >
      <i class="el-icon-close icon" @click="dialogGet=false"></i>
      <div class="operationBox">
        <el-button size="mini" type="primary" @click="saveGet()">选择</el-button>
        <el-button size="mini" @click="dialogGet=false">取消</el-button>
      </div>
      <div class="tableSearch tableSearchs">
        <el-form size="mini">
          <el-form-item label label-width="0">
            <el-input v-model="selectData.keyGet" placeholder="输入单据编号"></el-input>
          </el-form-item>
          <el-form-item label label-width="10px">
            <el-button type="primary" @click="searchGet">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :data="getArray"
        border
        ref="singleTable"
        highlight-current-row
        tooltip-effect="dark"
        @current-change="changeFunGet"
      >
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="outCode" label="单据编号" align="center"></el-table-column>
        <el-table-column prop="orderDate" label="日期" align="center"></el-table-column>
        <el-table-column prop="shopName" label="客户名称" align="center"></el-table-column>
      </el-table>
      <page-unit :pageData="pageDataSale" :func="getSaleOrderList"></page-unit>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import util from "@/util";
import pageUnit from "@/components/Page";
import {
  getRepositoryListPage,
  getRepertoryOutBoundListPage,
  getRepertoryOutBoundDetail,
  selfBuildOrderGoodsPurchaseReturn
} from "@/api";
export default {
  data() {
    return {
      tableData: [], // 物料数组
      formdata: {
        purchaseId: "",
        shopName: "",
        warehouseId: "",
        returnDate: "",
        orderDate: "",
        purchaseinCode: "",
        creator: "",
        remark: "",
        returnAmount: 0,
        returnNum: 0,
        freight: 0,
        amount: 0
      },
      cangArray: [], // 入库仓库数组
      selectData: {
        keyGet: ""
      },
      dialogGet: false, // 取来源单弹窗
      selectionGet: {}, // 选择的来源单
      getArray: [], // 取来源单数组
      rules: {
        returnDate: [
          { required: true, message: "请选择退货日期", trigger: "blur" }
        ],
        orderDate: [{ required: true }]
      },
      pageDataSale: {
        pageSize: 20,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      }
    };
  },
  components: { pageUnit },
  computed: {
    ...mapState({
      merchantId: state => state.merchantId,
      linkName: state => state.linkName,
      companyName: state => state.companyName,
      userId: state => state.userId
    }),
    returnAmount: function() {
      let num = 0;
      let totalPrice = 0;
      this.tableData.forEach(i => {
        num += Number(i.returnNum);
        totalPrice += Number(i.returnNum) * Number(i.goodsPrice);
        i.goodsAmount = (Number(i.returnNum) * Number(i.goodsPrice)).toFixed(2);
      });
      this.formdata.returnNum = num;
      this.formdata.returnAmount = totalPrice.toFixed(2);
      return isNaN(totalPrice) ? 0 : totalPrice.toFixed(2);
    },
    formdataAllTotal: function() {
      let totalPrice = 0;
      this.tableData.forEach(i => {
        totalPrice += Number(i.returnNum) * Number(i.goodsPrice);
      });
      totalPrice += Number(this.formdata.freight);
      if (totalPrice == NaN || totalPrice == 0) {
        this.formdata.amount = 0;
        return totalPrice.toFixed(2);
      } else {
        this.formdata.amount = totalPrice.toFixed(2);
        return totalPrice.toFixed(2);
      }
    }
  },
  mounted() {
    this.init();
    this.repertory();
  },
  methods: {
    // 选择仓库
    getwarehouseName(val) {
      this.cangArray.forEach(ele => {
        if (ele.id == val) {
          if (ele.openingInventoryState == 0) {
            this.$message({
              type: "error",
              message: "该仓库未录入期初库存"
            });
            this.formdata.warehouseId = "";
          }
        }
      });
    },
    // 日期转化
    // tim (row) {
    //   return util.foryear(parseInt(row.orderDate));
    // },
    // 获取入库仓库列表
    repertory() {
      let data = {
        shopId: this.merchantId,
        nameCode: "",
        openingInventoryState: 1,
        status: "0"
      };
      getRepositoryListPage(data).then(res => {
        this.cangArray = res.data.list;
      });
    },
    // 获取当日日期
    getNowFormatDate() {
      new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10);
      const date = new Date();
      var datas = date.setTime(date.getTime());
      var datase = util.foryear(parseInt(datas));
      this.formdata.orderDate = datase;
    },
    init() {
      this.getNowFormatDate(); // 默认单据日期为当天日期
      this.formdata.purchaseStatus = "1"; // 默认单据状态为已生成
      this.formdata.creator = this.linkName; // 获取当前登录用户名
    },
    // 点击保存，先验证表单
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleSave();
        } else {
          return false;
        }
      });
    },
    // 提交表单
    handleSave() {
      if (this.tableData.length == 0 || !this.tableData[0].goodsId) {
        this.$message({
          type: "error",
          message: "商品不能为空"
        });
        return false;
      }
      for (let i = 0; i < this.tableData.length; i++) {
        if (Number(this.tableData[i].returnNum) <= 0) {
          this.$message({
            type: "error",
            message: "商品数量不能小于等于0"
          });
          return false;
        }
        this.tableData[i].goodsNum = this.tableData[i].returnNum;
        this.tableData[i].goodsDetailId=this.tableData[i].id;
      }
      selfBuildOrderGoodsPurchaseReturn({
        shopId: this.formdata.shopId,
        shopName: this.formdata.shopName,
        purchaseId: this.formdata.purchaseId,
        warehouseId: this.formdata.warehouseId,
        warehouseName: this.formdata.warehouseName,
        supplierId: this.merchantId,
        supplierName: this.companyName,
        orderDate: this.formdata.orderDate,
        creator: this.userId,
        returnAmount: this.formdata.returnAmount,
        returnNum: this.formdata.returnNum,
        amount: this.formdata.amount,
        freight: this.formdata.freight,
        remark: this.formdata.remark,
        returnDate: this.formdata.returnDate,
        purchaseType: 0,
        goodsList: JSON.stringify(this.tableData),
        type: 1
      }).then(res => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: res.msg
          });
          util.routerTo("/order-center/sale-management/sale-deliveryOrder");
        }
      });
    },
    // 获取销售出库列表数据
    getSaleOrderList(pageSize, pageNum) {
      getRepertoryOutBoundListPage({
        pageNum: pageNum,
        pageSize: pageSize,
        shopId: this.merchantId,
        outStatus: 4,
        outType: 1,
        outCode: this.selectData.keyGet,
        isSelf: "1"
      }).then(res => {
        this.getArray = res.data.list;
        this.pageDataSale.totalItems = res.data.pageTotal;
        this.dialogGet = true;
      });
    },
    // 点击返回按钮
    goBack() {
      history.back();
    },
    // 取来源单相关操作
    // 取来源单
    healthOrder() {
      this.getSaleOrderList(this.pageDataSale.pageSize, 1);
      this.dialogGet = true;
    },
    changeFunGet(val) {
      this.selectionGet = val;
    },
    searchGet() {
      this.getSaleOrderList(this.pageDataSale.pageSize, 1);
    },
    saveGet() {
      getRepertoryOutBoundDetail({
        id: this.selectionGet.id,
        shopId:this.merchantId,
        returnNum: "1"
      }).then(res => {
        this.formdata.shopName = res.data.shopName;
        this.formdata.shopId = res.data.shopId;
        this.formdata.warehouseId = res.data.warehouseId;
        this.formdata.warehouseName = res.data.warehouseName;
        this.tableData = res.data.goodsList;
        this.formdata.freight = 0;
        this.formdata.purchaseId = res.data.id;
      });
      this.dialogGet = false;
    },
    // 删除表格中选中的物料
    handleCancel(index) {
      this.tableData.splice(index, 1);
    }
  }
};
</script>
<style scoped>
.th-right {
  margin-top: 20px;
}
</style>
